<script lang="ts" setup>
import { QForm, QTable, type FormItemRows, type TableColums } from '@meetjs/element-plus-kit'
import { checkPermission } from '@/utils/permission'
import { warnBox } from '@/utils/utils'
import type { IGetDictsRes } from '@/api/system/dict/type'
import { listJobLog, delJobLog, cleanJobLog, jobLogExport, getJobById } from '@/api/monitor/job'
import { downloadBlobFile } from '@/utils'
import { debounce } from 'es-toolkit'
import { getDicts } from '@/api/system/dict'
import { formatDate } from '@/utils/day'
import { useTagsViewStore } from '@/store/tagsView'

const tagsViewStore = useTagsViewStore()
const route = useRoute()
const router = useRouter()

const jobGroupOptions = ref<IGetDictsRes>([])
const statusOptions = ref<IGetDictsRes>([])

// form
const formValue = ref<any>({
	jobName: '',
	jobGroup: '',
	status: '',
	daterange: []
})

const formOptions = ref<FormItemRows[]>([
	{
		type: 'input',
		label: '任务名称',
		prop: 'jobName',
		attrs: {
			placeholder: '请输入任务名称'
		}
	},
	{
		type: 'select',
		label: '任务组名',
		prop: 'jobGroup',
		options: jobGroupOptions as unknown as any[],
		attrs: {
			style: 'width: 200px',
			placeholder: '请选择任务组名'
		}
	},
	{
		type: 'select',
		label: '执行状态',
		prop: 'status',
		options: statusOptions as unknown as any[],
		attrs: {
			style: 'width: 200px',
			placeholder: '请选择执行状态'
		}
	},
	{
		type: 'date-picker',
		label: '执行时间',
		prop: 'daterange',
		attrs: {
			type: 'daterange',
			style: 'width: 240px',
			'start-placeholder': '开始日期',
			'end-placeholder': '结束日期'
		}
	}
])

// table
const loading = ref(false)
const page = ref({
	currentPage: 1,
	pageSize: 10,
	total: 0
})

const tableData = ref<any>([])
const selection = ref<string[]>([])

const columns = ref<TableColums[]>([
	{
		type: 'selection',
		width: '55',
		align: 'center'
	},
	{
		type: 'index',
		label: '序号',
		align: 'center',
		width: 60
	},
	{
		label: '日志编号',
		prop: 'jobLogId',
		width: '80px',
		showOverflowTooltip: true
	},
	{
		label: '任务名称',
		prop: 'jobName',
		showOverflowTooltip: true
	},
	{
		label: '任务组名',
		prop: 'jobGroup',
		type: 'slot'
	},
	{
		label: '调用目标字符串',
		prop: 'invokeTarget',
		showOverflowTooltip: true
	},
	{
		label: '日志信息',
		prop: 'jobMessage',
		showOverflowTooltip: true
	},
	{
		label: '执行状态',
		prop: 'status',
		type: 'slot'
	},
	{
		label: '执行时间',
		prop: 'createTime',
		formatter: row => formatDate(row.createTime)
	},
	{
		prop: 'action',
		fixed: 'right',
		label: '操作',
		width: '120px',
		align: 'center'
	}
])

// dialog
const open = ref(false)
const form = ref<any>({})

const getTableData = async () => {
	try {
		loading.value = true
		const params = {
			pageNum: page.value.currentPage,
			pageSize: page.value.pageSize,
			...formValue.value
		}

		if (params.daterange && params.daterange.length === 2) {
			params['params[beginTime]'] = params.daterange[0]
			params['params[endTime]'] = params.daterange[1]
			delete params.daterange
		}

		const res = await listJobLog(params)
		tableData.value = res.data.rows
		page.value.total = res.data.total
	} finally {
		loading.value = false
	}
}

const handleSelectionChange = (val: any[]) => {
	selection.value = val.map(item => item.jobLogId as string)
}

const multiple = computed(() => !(selection.value.length > 0))

const handleDelete = async () => {
	if (selection.value.length === 0) {
		ElMessage.warning('请选择要删除的数据')
		return
	}

	const ids = selection.value.join(',')
	await warnBox({
		title: '提示',
		message: `是否确认删除调度日志编号为"${ids}"的数据项?`
	})
	await delJobLog(ids)
	ElMessage.success('删除成功')
	getTableData()
}

const handleClean = async () => {
	await warnBox({
		title: '提示',
		message: '是否确认清空所有调度日志数据项?'
	})
	await cleanJobLog()
	ElMessage.success('清空成功')
	getTableData()
}

const handleExport = debounce(() => exportFn(), 800, {
	edges: ['leading']
})

const exportFn = () => {
	const params = {
		pageNum: page.value.currentPage,
		pageSize: page.value.pageSize,
		...formValue.value
	}

	if (params.daterange && params.daterange.length === 2) {
		params['params[beginTime]'] = params.daterange[0]
		params['params[endTime]'] = params.daterange[1]
		delete params.daterange
	}

	jobLogExport(params).then(data => {
		downloadBlobFile(data.data, data.filename ? data.filename : `job_log_${new Date().getTime()}.xlsx`)
	})
}

const handleClose = () => {
	tagsViewStore.delView({
		path: route.path,
		name: route.name as string
	})
	router.push('/monitor/job')
}

const handlePreview = (row: any) => {
	form.value = { ...row }
	open.value = true
}

function init() {
	getDicts('sys_sys_job_group').then(data => {
		jobGroupOptions.value = data
	})
	getDicts('sys_sys_job_status').then(data => {
		statusOptions.value = data
	})

	if (route.params.jobId && route.params.jobId !== '0') {
		getJobById(route.params.jobId as string).then(({ data }) => {
			formValue.value.jobName = data.jobName
			formValue.value.jobGroup = data.jobGroup
		})
	}
}

onMounted(() => {
	init()
	getTableData()
})
</script>

<template>
	<div class="tab-page-box">
		<div class="filter-box">
			<QForm
				inline
				:model="formValue"
				:form-options="formOptions"
				:buttons="['search', 'reset']"
				@search="getTableData"
				@reset="getTableData"
			/>
		</div>
		<div class="table-box">
			<QTable
				:data="tableData"
				:columns="columns"
				:page="page"
				:loading="loading"
				:selection="true"
				style="width: 100%"
				@selectionChange="handleSelectionChange"
				@pageChange="getTableData"
			>
				<template #headerLeft>
					<el-button
						v-if="checkPermission(['monitor:job:remove'])"
						:disabled="multiple"
						type="danger"
						@click="handleDelete"
					>
						删除
					</el-button>
					<el-button
						v-if="checkPermission(['monitor:job:remove'])"
						type="danger"
						@click="handleClean"
					>
						清空
					</el-button>
					<el-button
						v-if="checkPermission(['monitor:job:export'])"
						@click="handleExport"
					>
						导出
					</el-button>
					<el-button
						type="warning"
						@click="handleClose"
					>
						关闭页面
					</el-button>
				</template>
				<template #action="{ row }">
					<el-button
						v-if="checkPermission(['monitor:job:query'])"
						type="primary"
						link
						@click="handlePreview(row)"
					>
						详细
					</el-button>
				</template>
				<template #jobGroup="{ value }">
					<DictTag
						:value="value"
						:options="jobGroupOptions"
					/>
				</template>
				<template #status="{ row }">
					<DictTag
						:value="row.status"
						:options="statusOptions"
					/>
				</template>
			</QTable>
		</div>

		<!-- 调度日志详细 -->
		<el-dialog
			v-model="open"
			title="调度日志详细"
			width="700px"
			append-to-body
		>
			<el-form
				:model="form"
				label-width="100px"
			>
				<el-row>
					<el-col :span="12">
						<el-form-item label="日志序号：">{{ form.jobLogId }}</el-form-item>
						<el-form-item label="任务名称：">{{ form.jobName }}</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="任务分组：">{{ form.jobGroup }}</el-form-item>
						<el-form-item label="执行时间：">{{ form.createTime }}</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="调用方法：">{{ form.invokeTarget }}</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="日志信息：">{{ form.jobMessage }}</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="执行状态：">
							<div v-if="form.status == 0">正常</div>
							<div v-else-if="form.status == 1">失败</div>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item
							v-if="form.status == 1"
							label="异常信息："
						>
							{{ form.exceptionInfo }}
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="open = false">关 闭</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>
